import {Component, OnDestroy, OnInit} from '@angular/core';
import {Farm} from '../../../entity/farm.model';
import {FarmService} from '../../../service/farm.service';
import {FaultData} from '../../../entity/fault-data';
import {DataSourceService} from '../../../service/data-source/data-source.service';
import {ApplicationService} from '../../../service/application.service';
import {DeviceAlarm} from '../../../entity/alarm/alarm.model';

@Component({
  selector: 'app-alarm-lamp',
  templateUrl: './alarm-lamp.component.html',
  styleUrls: ['./alarm-lamp.component.css'],
  providers: [DataSourceService]
})
export class AlarmLampComponent implements OnInit, OnDestroy {
  private userId: number = 0;
  public fadeDiv: boolean = false;
  private farmId: number = -1;
  public farms: Farm[] = [];
  public alarmList: DeviceAlarm[] = [];
  public alarmListCache: DeviceAlarm[] = [];
  /**
   * 未确认的报警数目
   *
   * @type {number}
   * @memberof AlarmLampComponent
   */
  public alarmTotal: number = 0;

  public active1: boolean = true;
  public active3: boolean = false;

  /**
   * 描述（模糊查询字段）
   * @type {string}
   * @memberof AlarmLampComponent
   */
  public desc: string = '';
  /**
   * 类别（模糊查询字段）
   * @type {string}
   * @memberof AlarmLampComponent
   */
  public components: string = '';

  /**
   * 升压站总数
   */
  public substationDataTotal: number = 0;

  /**
   *报警定时器
   *
   * @private
   * @type {*}
   * @memberof AlarmLampComponent
   */
  alarmShowCount = 100;

  constructor(
    private dataSource: DataSourceService,
    private farmService: FarmService,
    private application: ApplicationService
  ) {
    this.userId = 1;
  }

  ngOnInit() {
    if (this.application.currentApplicationParams && this.application.currentApplicationParams['alarmShowCount']) {
      this.alarmShowCount = Number(this.application.currentApplicationParams['alarmShowCount'].paramValue);
    }
    this.loadData();
  }

  ngOnDestroy(): void {
    if (this.dataSource != null)
      this.dataSource.dispose();
  }


  public onFadeClick() {
    this.fadeDiv = !this.fadeDiv;
  }

  /**
   * 加载数据111
   *
   * @memberof AlarmLampComponent
   */
  private loadData() {
    Promise.all([
      this.farmService.getFarmsWithTotalTurbineByUserId(this.application.currentUser.userId)
    ]).then(res => {
      this.farms = res[0];
      this.subscribeAlarm();
    }).catch(error => {
      console.log('app-alarm-lamp has error', error);
    });
  }

  //升压站子组件给父组件传递的升压站总数
  onSubstationDataTotalChange(substationDataTotal) {
    this.substationDataTotal = substationDataTotal
  }

  /**
   * 订阅故障数据333
   *
   * @memberof AlarmLampComponent
   */
  private subscribeAlarm() {
    this.dataSource.alarm(this.userId).subscribe(next => {
      this.resolving(next);
    });
  }

  /**
   *
   *
   * 解析故障报警数据444
   *
   * @private
   * @param {FaultData[]} faultDatas 推送过来的数据
   * @param {*} timer
   * @memberof AlarmLampComponent
   */
  private resolving(data: DeviceAlarm[]) {
    data.forEach(d => {
      let flag = true;
      for (let i = 0, l = this.alarmListCache.length; i < l; i++) {
        let dd = this.alarmListCache[i]
        if (d.GN == dd.GN) {
          dd.faultLevelName = d.faultLevelName;
          dd.multipleValue = d.multipleValue;
          dd.faultBeginTime = d.faultBeginTime;
          dd.faultEndTime = d.faultEndTime;
          flag = false;
          break;
        }
      }
      if (flag) {
        this.alarmListCache.unshift(d);
      }
    });
    this.alarmList = [];
    for (let i = 0, l = this.alarmListCache.length; i < l; i++) {
      let dd = this.alarmListCache[i];
      if (this.components && this.desc) {
        if ((dd.krCode.indexOf(this.components) > -1) && (dd.faultDesc.indexOf(this.desc) > -1)) {
          if (this.farmId == -1 || this.farmId == dd.farmId) {
            this.alarmList.push(dd);
          }
        }
      } else if (this.components) {
        if (dd.krCode.indexOf(this.components) > -1) {
          if (this.farmId == -1 || this.farmId == dd.farmId) {
            this.alarmList.push(dd);
          }
        }
      } else if (this.desc) {
        if (dd.faultDesc.indexOf(this.desc) > -1) {
          if (this.farmId == -1 || this.farmId == dd.farmId) {
            this.alarmList.push(dd);
          }
        }
      } else {
        if (this.farmId == -1 || this.farmId == dd.farmId) {
          this.alarmList.push(dd);
        }
      }
    }
    this.alarmTotal = this.alarmListCache.length;
    if (this.alarmTotal > this.alarmShowCount) {
      this.alarmList = this.alarmList.slice(0, this.alarmShowCount);
    }
  }

  /**
   * 关闭alarm弹框
   *
   * @memberof AlarmLampComponent
   */
  public onClickCloseAlarm() {
    this.fadeDiv = false;
  }

  /**
   * tab切换（点击 预警、报警切换事件）
   *
   * @memberof AlarmLampComponent
   */
  isActive(number) {
    // this.active = (number == 1) ? true : false;
    switch (number) {
      case 1:
        this.active1 = true;
        this.active3 = false;
        break;
      default:
        this.active1 = false;
        this.active3 = true;
    }
  }

  onChangeFarm(ev) {
    this.farmId = ev;
  }
}

